package com.hiabr.iep.common.web.interceptor;

import com.alibaba.fastjson.JSON;
import com.hiabr.iep.common.domain.constant.CommonConstant;
import com.hiabr.iep.common.domain.context.ThreadLocalContext;
import com.hiabr.iep.common.utils.RequestUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import javax.servlet.http.HttpServletRequest;

/**
 * description: FeignInterceptor
 */
@Slf4j
@Configuration
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
        HttpServletRequest request = RequestUtil.getHttpServletRequest();
        if (request != null) {
            requestTemplate.header(CommonConstant.TRACE_ID, request.getHeader(CommonConstant.TRACE_ID));
            requestTemplate.header(CommonConstant.USER, request.getHeader(CommonConstant.USER));
            requestTemplate.header(CommonConstant.ADMIN, request.getHeader(CommonConstant.ADMIN));
        } else {
            //防止异步fegin调用无法获取request问题
            requestTemplate.header(CommonConstant.TRACE_ID, ThreadLocalContext.getTraceId());
            requestTemplate.header(CommonConstant.USER, JSON.toJSONString(ThreadLocalContext.getUser()));
            requestTemplate.header(CommonConstant.ADMIN, JSON.toJSONString(ThreadLocalContext.getAdmin()));
        }
    }

}
